<template>
  <div class="tree-chat-content">
    <div class="haspadding">
      <div class="allData" v-if="!isback">
        <div class="info-box">
          <p class="num" style="color: #2c84ff">{{ device.sumCamera }}</p>
          <p class="text">设备总数/台</p>
        </div>
        <div class="info-box">
          <p class="num" style="color: #00b960">{{ device.onlineCamera }}</p>
          <p class="text">在线数/台</p>
        </div>
        <div class="info-box">
          <p class="num" style="color: #ff0606">{{ device.offlineCamera }}</p>
          <p class="text">离线数/台</p>
        </div>
      </div>
    </div>
    <div class="haspadding">
      <div class="tab-box">
        <div
          class="tab-item"
          @click="selectTab('address')"
          :class="{ active: currentTab == 'address' }"
        >
          安装位置
        </div>
        <div
          class="tab-item"
          @click="selectTab('sence')"
          :class="{ active: currentTab == 'sence' }"
        >
          治理场景
        </div>
        <div
          class="tab-item"
          @click="selectTab('area')"
          :class="{ active: currentTab == 'area' }"
        >
          管理责任
        </div>
      </div>
      <el-input
        v-model="keyword"
        style="width: 100%"
        placeholder="请输入查询的设备"
      >
        <template #append>
          <el-icon color="#fff"><Search /></el-icon>
        </template>
      </el-input>
    </div>
    <div class="haspadding l-list" style="margin-top: 16px">
      <div class="l-list" :class="{ isbacklist: isback }">
        <el-tree
          v-if="currentTab == 'address'"
          ref="treeRef"
          class="tree-select"
          style="width: 100%; min-width: fit-content"
          :data="treeData"
          :filter-node-method="filterNode"
          node-key="nodeId"
          highlight-current
          :props="defaultProps"
          @check="checkTree"
          @node-click="selectTreeNode"
          :render-content="renderContent"
          :default-expanded-keys="defaultData"
        >
          <template #default="{ data }">
            <span :title="data.nodeName">{{ data.nodeName }}</span>
          </template>
        </el-tree>
        <el-tree
          v-if="currentTab == 'sence'"
          ref="treeRef"
          class="tree-select"
          style="width: 100%; min-width: fit-content"
          :data="treeData"
          :filter-node-method="filterNode"
          node-key="nodeId"
          highlight-current
          :props="defaultProps"
          @check="checkTree"
          @node-click="selectTreeNode"
          :render-content="renderContent"
          :default-expanded-keys="defaultData"
        >
          <template #default="{ data }">
            <span :title="data.nodeName">{{ data.nodeName }}</span>
          </template>
        </el-tree>
        <el-tree
          v-if="currentTab == 'area'"
          ref="treeRef"
          class="tree-select"
          style="width: 100%; min-width: fit-content"
          :data="treeData"
          :filter-node-method="filterNode"
          node-key="nodeId"
          highlight-current
          :props="defaultProps"
          @check="checkTree"
          @node-click="selectTreeNode"
          :render-content="renderContent"
          :default-expanded-keys="defaultData"
        >
          <template #default="{ data }">
            <span :title="data.nodeName">{{ data.nodeName }}</span>
          </template>
        </el-tree>
      </div>
    </div>
    <div class="panel-btn" v-if="isback">
      <div class="title-b">选择回放时间</div>
      <div class="selectTime" v-if="isback">
        <el-date-picker
          style="width: 70%"
          v-model="backTime"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          class="leftPop"
        />
        <div class="confirm-btn" @click="confirmPointOne">查询</div>
      </div>
    </div>
    <div>
      <ptz
        v-if="!isback && pztPoint.funcType == '2'"
        :did="{ tag: currentCode }"
      />
    </div>
  </div>
</template>
<script setup>
import { ElMessage } from "element-plus";
import { defineAsyncComponent, onMounted, reactive } from "vue";
import { getPointListZr } from "@/api/event.js";
import {
  getSencePointList,
  getPointListAddress,
  getDeviceCount,
} from "@/api/video.js";
import ptz from "@/components/video/ptz.vue";
import online from "@/assets/video/online.png";
import outline from "@/assets/video/outline.png";
const route = useRoute(); // 获取当前路由信息
const emit = defineEmits(["selectNode", "selectBackTime", "selectOneNode"]);

const props = defineProps({
  ptzCode: String,
});

const defaultProps = {
  children: "childrens",
  label: function (data, node) {
    return data.nodeName;
  },
};

let treeData = ref([]);
let defaultData = ref([]);
const getData = async () => {
  try {
    if (currentTab.value == "sence") {
      let { data } = await getSencePointList({});
      defaultData.value = [data.treeNodeList[0].nodeId]; // 默认展开第一个节点
      treeData.value = data.treeNodeList;
    } else if (currentTab.value == "address") {
      let { data } = await getPointListAddress({});
      defaultData.value = [data.deviceOrgTree[0].nodeId]; // 默认展开第一个节点
      treeData.value = data.deviceOrgTree;
    } else {
      let { data } = await getPointListZr({});
      defaultData.value = [data.deviceOrgTree[0].nodeId]; // 默认展开第一个节点
      treeData.value = data.deviceOrgTree;
    }
  } catch (e) {
    console.error(e);
  }
};

let checkedKeys = ref([]);
let timer = null;

let currentTab = ref("address");

const selectTab = (type) => {
  keyword.value = "";
  currentTab.value = type;
  getData();
};
let treeRef = ref();
let keyword = ref("");
watch(keyword, (val) => {
  treeRef.value.filter(val);
});

const filterNode = (value, data) => {
  if (!value) return true;
  return data.nodeName.includes(value);
};

// 自定义渲染节点内容，高亮匹配文本
const renderContent = (h, { node, data }) => {
  const { label } = node;
  const searchText = keyword.value;
console.log(data.cameraState)
  // 如果没有搜索内容，直接返回原始文本
  if (!searchText) {
    return h(
      "span",
      {
        title: node.label, // 鼠标悬停时显示完整文本
        style: { display: "flex", alignItems: "center" },
      },
      [
        h("img", {
          src: data.cameraState == '1' ? online : data.cameraState == '0' ? outline : "",
          style: {
            marginRight: "5px",
            verticalAlign: "middle",
            display: data.tag ? "inline-block" : "none",
          },
        }),
        node.label,
      ]
    );
  }

  // 找到匹配的文本位置
  const index = label.toLowerCase().indexOf(searchText.toLowerCase());
  if (index === -1) {
    return h(
      "span",
      {
        title: node.label, // 鼠标悬停时显示完整文本
      },
      [
        h("img", {
          src:  data.cameraState == '1' ? online : data.cameraState == '0' ? outline : "",
          style: {
            marginRight: "5px",
            verticalAlign: "middle",
            display: data.tag ? "inline-block" : "none",
          },
        }),
        node.label,
      ]
    ); // 不匹配，返回原始文本
  }

  // 分割文本：匹配前 + 匹配部分（红色） + 匹配后
  const beforeStr = label.substring(0, index);
  const matchStr = label.substring(index, index + searchText.length);
  const afterStr = label.substring(index + searchText.length);

  return h("span", [
    h("img", {
      src: data.cameraState == '1' ? online : data.cameraState == '0' ? outline : "",
      style: {
        marginRight: "5px",
        verticalAlign: "middle",
        display: data.tag ? "inline-block" : "none",
      },
    }),
    beforeStr,
    h(
      "span",
      {
        style: { color: "#FF9200" },
        title: node.label, // 鼠标悬停时显示完整文本
      },
      matchStr
    ),
    afterStr,
  ]);
};

let backTime1 = ref("");
let backTime2 = ref("");
let backTime = ref([]);
let isback = ref(false);

let currentCode = ref("");
function findNodeByTag(data, targetTag) {
  // 检查当前节点是否有匹配的tag
  if (data.tag === targetTag) {
    return data;
  }
  // 如果有子节点，递归查找
  if (data.childrens && Array.isArray(data.childrens)) {
    for (const child of data.childrens) {
      const found = findNodeByTag(child, targetTag);
      if (found) {
        return found;
      }
    }
  }
  // 如果没有找到，返回null
  return null;
}
// 根据id获取当前选中的节点
const pztPoint = ref({});
const getNode = async (data) => {
  if (treeData.value.length > 0) {
    let result = await findNodeByTag(treeData.value[0], data);
    console.log("result", result);
    pztPoint.value = result;
  }
};

watch(
  () => props.ptzCode,
  (newval) => {
    currentCode.value = newval;
    getNode(newval);
  },
  {
    deep: true,
    immediate: true,
  }
);

const confirmPoint = () => {
  let nodes = treeRef.value.getCheckedNodes();
  let list = [];
  nodes.forEach((element) => {
    if (element.tag) {
      // list.push(element.tag);
      list.push(element);
    }
  });
  if (list.length == 0) {
    currentCode.value = "";
    emit("selectNode", []);
    return;
  }
  emit("selectNode", list);
  if (isback.value) {
    if (backTime.value.length < 2) {
      ElMessage.error("请选择时间节点");
      return;
    }
    emit("selectBackTime", [
      new Date(backTime.value[0]).getTime() + "",
      new Date(backTime.value[1]).getTime() + "",
    ]);
  }
};

const confirmPointOne = () => {
  if (backTime.value.length < 2) {
    ElMessage.error("请选择时间节点");
    return;
  }
  let node = treeRef.value.getCurrentNode();
  emit("selectBackTime", [
    new Date(backTime.value[0]).getTime() + "",
    new Date(backTime.value[1]).getTime() + "",
  ]);
  debugger;
  if (node.tag) {
    emit("selectOneNode", node);
  }
};

let timers = null;
const checkTree = (data, node) => {
  if (isback.value) return;
  if (timers) {
    clearTimeout(timers);
    timers = null;
  }
  timers = setTimeout(() => {
    confirmPoint();
  }, 300);
};

// 单选点
const selectTreeNode = (data, node) => {
  if (isback.value) return;
  if (data.tag) {
    emit("selectOneNode", data);
  }
};

let device = reactive({
  sumCamera: 0,
  onlineCamera: 0,
  offlineCamera: 0,
});

const getCount = async () => {
  try {
    let { data } = await getDeviceCount({});
    Object.assign(device, data);
  } catch (e) {
    console.error(e);
  }
};

onMounted(() => {
  getData();
  getCount();
  if (route.params.type == "back") {
    isback.value = true;
  }
});

onUnmounted(() => {});
</script>

<style lang="scss" scoped>
.tree-chat-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding-top: 21px;
  .haspadding {
    padding: 0 28px;
  }
  .l-list {
    width: 100%;
    // height: calc(100% - 146px);
    flex: 1;
    overflow: auto;
    &.isbacklist {
      // height: calc(100% - 226px);
    }
  }
  .allData {
    width: 100%;
    height: 75px;
    display: flex;
    align-items: center;
    justify-content: space-around;
    background: url("@/assets/video/tbg.png") no-repeat;
    background-size: 100% 100%;
    margin-bottom: 16px;
    .num {
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      font-size: 18px;
      text-align: center;
    }
    .text {
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      font-size: 12px;
      color: #666666;
      text-align: center;
    }
  }
}
</style>

<style lang="scss">
.tab-box {
  cursor: pointer;
  width: 100%;
  height: 32px;
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  .tab-item {
    width: 33%;
    font-size: 14px;
    color: #2263bf;
    line-height: 32px;
    text-align: center;
    background: #ffffff;
    box-shadow: 0px 0px 5px 0px rgba(70, 102, 149, 0.12);
    &.active {
      color: #fff;
      background: #2263bf;
      border-radius: 6px 0px 0px 6px;
      border-radius: 3px;
      border: 1px solid rgba(34, 99, 191, 0.09);
    }
  }
}
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background: #edf5ff;
  color: #2263bf;
}
.el-input-group__append {
  width: 31px;
  background: #2263bf;
  padding: 0;
}
.panel-btn {
  height: 150px;
  padding-top: 10px;
  .title-b {
    width: 375px;
    height: 38px;
    background: rgba(142, 191, 255, 0.32);
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    font-size: 14px;
    color: #2263bf;
    padding-left: 22px;
    line-height: 38px;
  }
  .selectTime {
    display: flex;
    align-items: center;
    padding: 30px 16px;
    .confirm-btn {
      width: 82px;
      height: 30px;
      line-height: 30px;
      background: #2263bf;
      border-radius: 3px;
      margin-left: 10px;
    }
  }
}
</style>
